<template>
  <div class="kzgl-container">
    <ComOpenlayersMap ref="map" @mapInited="mapInited"></ComOpenlayersMap>
    <!-- 标题 -->
    <div class="navbar" :style="{ position: 'absolute', top: statusBarHeight + 'px', left: 0, right: 0 }">
      <van-image
        width="20px"
        height="20px"
        fit="contain"
        :src="require('../../assets/ic_arrow_left_white.png')"
        @click="goBack" />
      <span class="navbar-title">矿政管理</span>
      <span class="navbar-right-text" @click="toStatistics">统计</span>
    </div>
    <div class="top-left">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="openKSList">
          <van-image
            width="1rem"
            height="1rem"
            fit="contain"
            :src="require('../../assets/map_btn_list.png')"
            style="padding: 0.125rem" />
          <div class="icon-name">矿山列表</div>
        </div>
      </div>
    </div>
    <div class="top-right">
      <div class="btn-icon-group">
        <van-popover v-model="showLayerPopover" trigger="click" placement="left-start" @open="openLayerPopover">
          <div class="layer-box">
            <van-image
              class="layer-yx"
              width="2.5rem"
              height="2.5rem"
              fit="contain"
              :src="require(layerType == 'YX' ? '../../assets/ic_yx_selected.png' : '../../assets/ic_yx_default.png')"
              @click="changeBaseLayer('YX')" />
            <van-image
              class="layer-sl"
              width="2.5rem"
              height="2.5rem"
              fit="contain"
              :src="require(layerType == 'SL' ? '../../assets/ic_sl_selected.png' : '../../assets/ic_sl_default.png')"
              @click="changeBaseLayer('SL')" />
          </div>
          <template #reference>
            <div class="btn-icon" @click="tcthShow = true">
              <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/layer.png')" />
              <div class="icon-name">切换图层</div>
            </div>
          </template>
        </van-popover>
      </div>
    </div>
    <div class="left-bottom">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="jurisdiction">
          <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/jurisdiction.png')" />
          <div class="icon-name">我的辖区</div>
        </div>
      </div>
    </div>
    <div class="right-bottom">
      <div class="btn-icon-group">
        <div class="btn-icon" @click="positionSelf">
          <van-image width="1.25rem" height="1.25rem" fit="contain" :src="require('../../assets/myposition.png')" />
          <div class="icon-name">我的位置</div>
        </div>
      </div>
    </div>
    <!-- 统计 -->
    <ComKsStatistic
      v-show="isShowStatistic"
      :chartData="chartData"
      @closeStatistic="isShowStatistic = false"
      :style="{ position: 'absolute', top: statusBarHeight + 'px', left: 0, right: 0, bottom: 0 }"></ComKsStatistic>
    <!-- 地图监控数量聚合模板 -->
    <div v-for="item in ksList" :key="item.xzqdm" :id="`region-${item.xzqdm}`" class="region-container">
      <!-- 左侧图片 -->
      <img class="region-icon" :src="require('../../assets/map-mine.png')" />
      <!-- 右侧文本信息 -->
      <div class="region-text-container flexY flex1">
        <div class="region-xzqmc">{{ item.xzqmc }}</div>
        <div class="region-count">{{ item.counts }}</div>
      </div>
    </div>
    <!-- 矿山基本信息弹窗 -->
    <van-popup v-model="isShowKSInfoPopup" round>
      <div class="ks-container">
        <div class="ks-title-box">
          <span></span>
          <span class="ks-title-text">矿山基本信息</span>
          <van-image
            width="20"
            height="20"
            fit="contain"
            :src="require('../../assets/ic_close_black.png')"
            @click="isShowKSInfoPopup = false" />
        </div>
        <van-field
          label-width="100"
          :label="ksItem.label"
          :value="ksItem.value"
          readonly
          input-align="right"
          v-for="ksItem in ksBaseInfo"
          :key="ksItem.label"
          autosize />
      </div>
    </van-popup>
    <!-- 重叠图斑 选择图斑弹窗 -->
    <van-dialog
      v-model="showKSTBDialog"
      title="选择目标矿厂（单选）"
      show-cancel-button
      confirm-button-text="确认"
      @confirm="onKSConfirm">
      <van-radio-group v-model="currentKSTbbsm" style="height: 20rem; overflow: scroll">
        <van-radio
          style="padding: 0.5rem 1rem; word-break: break-all"
          :name="item.tbbsm"
          v-for="item in chooseKSFeatures"
          :key="item.tbbsm"
          shape="square">
          {{ item.ksmc }}
        </van-radio>
      </van-radio-group>
    </van-dialog>

    <!-- 矿山列表弹窗 -->
    <van-popup
      v-model="isShowKSListPopup"
      position="left"
      :style="{ width: '70%', height: '100%', paddingTop: `${statusBarHeight}px`, boxSizing: 'border-box' }">
      <van-collapse v-model="ksListActiveNames" accordion>
        <van-collapse-item
          :icon="ksListActiveNames.includes(xzqItem.xzqdm) ? expandImg : collapseImg"
          :title="xzqItem.xzqmc"
          :name="xzqItem.xzqdm"
          :value="xzqItem.counts"
          v-for="xzqItem in ksList"
          :key="xzqItem.xzqdm">
          <div class="ks-item" v-for="ksItem in xzqItem.kslist" :key="ksItem.tbbsm" @click="ksItemClick(ksItem)">
            {{ ksItem.ksmc }}
          </div>
        </van-collapse-item>
      </van-collapse>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ComOpenlayersMap from '../../components/com-openlayers-map.vue'
import { getKsStatistics, getKsPieChart } from '@/api'
import ComKsStatistic from '../../components/com-ks-statistic.vue'

export default {
  components: { ComOpenlayersMap, ComKsStatistic },
  data() {
    return {
      olMap: null,
      olView: null,
      layerMap: null,
      statusBarHeight: 24,
      showLayerPopover: false,
      layerType: 'YX', //YX 影像底图 SL 矢量底图
      mapOverlayList: [],
      isShowKSInfoPopup: false,
      preKSFeature: null,
      chooseKSFeatures: [],
      currentKSTbbsm: '',
      showKSTBDialog: false,
      ksBaseInfo: [],
      ksList: [],
      isShowKSListPopup: false,
      ksListActiveNames: [],
      expandImg: require('../../assets/ic_expand.png'),
      collapseImg: require('../../assets/ic_collapse.png'),
      isShowStatistic: false,
      chartData: []
    }
  },
  computed: {
    ...mapGetters(['getNativeApi', 'getNativeCallJs', 'getUserInfo'])
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getNativeCallJs.registerNativieGoBack(() => {
        vm.goBack()
      })
    })
  },
  created() {
    this.setStatusBarState()
    this.getKsList()
  },
  methods: {
    setStatusBarState() {
      this.getNativeApi.setStatusBarColor('#FFFFFF')
      this.getNativeApi.setStatusBarLightMode(true)
      this.getNativeApi.getStatusBarHeight().then(result => {
        this.statusBarHeight = result.data
      })
    },
    mapInited(map, view) {
      this.olMap = map
      this.olView = view
      this.layerMap = this.$refs.map.getLayerMap()
      this.$refs.map.addSingleClick(e => {
        const features = this.olMap.getFeaturesAtPixel(e.pixel, {
          hitTolerance: 30
        })
        if (features.length == 0) {
          return
        }
        const ksFeature = features.filter(item => item.get('layername') == 'KSSHAPE')

        if (ksFeature.length <= 0) {
          return
        } else if (ksFeature.length == 1) {
          this.showKSInfo(ksFeature[0])
        } else {
          this.chooseKSFeatures = ksFeature.map(feature => {
            const properties = feature.getProperties()
            return { feature: feature, ksmc: properties['ksmc'], tbbsm: properties['tbbsm'] }
          })
          this.showKSTBDialog = true
        }
      })
      this.$refs.map.changeResolution(() => {
        const zoom = this.olView.getZoom()
        if (zoom < 10) {
          this.togglemapOverlay(true)
          this.layerMap['KSSHAPE'].setVisible(false)
          this.layerMap['XZQSHAPE'].setVisible(true)
        } else {
          this.togglemapOverlay(false)
          this.layerMap['KSSHAPE'].setVisible(true)
          this.layerMap['XZQSHAPE'].setVisible(false)
        }
      })

      this.drawXZQShape()
    },
    // 在地图上绘制带有背景图的区域
    drawRegionsOnMap() {
      this.mapOverlayList = []
      this.ksList.forEach(item => {
        // 获取template中预定义的元素
        const element = document.getElementById(`region-${item.xzqdm}`)
        // 创建覆盖物
        const overlay = this.$refs.map.createOverlay(element, [item.longitude, item.latitude], {
          positioning: 'bottom-center',
          offset: [0, 20] // 调整位置，使其显示在点的上方
        })
        // 将覆盖物添加到地图
        this.olMap.addOverlay(overlay)
        this.mapOverlayList.push(overlay)
      })
    },

    // 清除地图上的区域
    togglemapOverlay(visible = false) {
      this.mapOverlayList.forEach(item => {
        // item.setVisible(visible)
        item.setMap(visible ? this.olMap : null)
      })
    },
    drawXZQShape() {
      for (const xzqItem of this.getUserInfo.wkt) {
        const feature = this.$refs.map.createXZQFeature(xzqItem.wkt)
        feature.setProperties(xzqItem)
        feature.setId(xzqItem.xdm)
        feature.set('layername', 'XZQSHAPE')
        const defalutStyle = this.$refs.map.getXZQDefalutStyle()
        feature.setStyle(defalutStyle)
        this.layerMap['XZQSHAPE'].getSource().addFeature(feature)
      }
    },
    drawKSShape() {
      for (const xzqItem of this.ksList) {
        for (const ksItem of xzqItem.kslist) {
          if (ksItem.wktlist.length <= 0) {
            continue
          }
          const feature = this.$refs.map.createGeometryCollection(ksItem.wktlist.map(shape => shape.wkt))
          feature.setProperties(ksItem)
          feature.setId(ksItem.tbbsm)
          feature.set('layername', 'KSSHAPE')
          const defalutStyle = this.$refs.map.getKSDefalutStyle(ksItem.ksmc)
          feature.setStyle(defalutStyle)
          this.layerMap['KSSHAPE'].getSource().addFeature(feature)
        }
      }
    },
    changeBaseLayer(layerType) {
      if (this.layerType == layerType) {
        return
      }
      this.layerType = layerType
      this.$refs.map.changeBaseLayer(layerType)
    },
    openLayerPopover() {
      this.showLayerPopover = true
    },
    positionSelf() {
      this.$refs.map.positionSelf()
    },
    jurisdiction() {
      const xzqInfo = this.getUserInfo.hcqy
      this.$refs.map.jurisdiction(xzqInfo.minx, xzqInfo.maxx, xzqInfo.miny, xzqInfo.maxy)
    },
    goBack() {
      if (this.isShowStatistic) {
        this.isShowStatistic = false
      } else {
        this.$router.go(-1)
      }
    },
    onKSConfirm() {
      if (this.currentKSTbbsm == '') {
        this.$toast('请选择目标矿山')
        return
      }
      const featureItem = this.chooseKSFeatures.find(featureItem => featureItem.tbbsm == this.currentKSTbbsm)
      this.showKSInfo(featureItem.feature)
      this.currentKSTbbsm = ''
    },
    getKsList() {
      getKsStatistics()
        .then(res => {
          this.ksList = res.data
          this.chartData = this.ksList.map(item => ({ xzqdm: item.xzqdm, xzqmc: item.xzqmc, value: item.counts }))
          setTimeout(() => {
            this.drawRegionsOnMap()
            this.drawKSShape()
          }, 500)
        })
        .catch(err => {
          console.log('获取矿山列表失败')
        })
    },
    showKSInfo(feature) {
      const properties = feature.getProperties()
      const geometryCollection = feature.getGeometry()
      const extent = geometryCollection.getExtent()
      this.olView.fit(extent, {
        padding: [50, 50, 50, 50], // 可选：添加内边距，避免元素贴边
        duration: 500 // 可选：动画过渡时间（毫秒）
      })
      this.ksBaseInfo = [
        {
          label: '业务号',
          value: properties['ywh']
        },
        {
          label: '矿山名称',
          value: properties['ksmc']
        },
        {
          label: '矿山地址',
          value: properties['ksdz']
        },
        {
          label: '矿权人',
          value: properties['kqr']
        },
        {
          label: '统一社会信用代码',
          value: properties['tyskxydm']
        },
        {
          label: '采矿许可证号',
          value: properties['xkzh']
        },
        {
          label: '权利期限',
          value: `${properties['qxdqstart']}-${properties['qxdqend']}`
        },
        {
          label: '矿区面积(‌km²)',
          value: properties['kqmj']
        },
        {
          label: '开采深度',
          value: `${properties['kcsdup']}米至${properties['kcsddown']}米`
        },
        {
          label: '开采主矿种',
          value: properties['kczkzmc']
        },
        {
          label: '共伴生矿种',
          value: properties['gbskzmc']
        }
      ]
      if (this.preKSFeature) {
        const preProperties = this.preKSFeature.getProperties()
        this.preKSFeature.setStyle(this.$refs.map.getKSDefalutStyle(preProperties['ksmc']))
      }
      feature.setStyle(this.$refs.map.getKSSelectedStyle(properties['ksmc']))
      this.preKSFeature = feature
      setTimeout(() => {
        this.isShowKSInfoPopup = true
      }, 1000)
    },

    toStatistics() {
      this.isShowStatistic = true
    },
    openKSList() {
      this.isShowKSListPopup = true
    },
    ksItemClick(ksItem) {
      this.isShowKSListPopup = false
      const ksFeature = this.layerMap['KSSHAPE'].getSource().getFeatureById(ksItem.tbbsm)
      if (ksFeature) {
        this.showKSInfo(ksFeature)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.kzgl-container {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.navbar {
  width: calc(100vw - 24px);
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(0, 0, 0, 0.2);
  padding: 0 12px;
}
.navbar-title {
  font-weight: 800;
  font-size: 18px;
  color: #ffffff;
}
.navbar-right-text {
  font-size: 14px;
  color: #ffffff;
}
.top-left {
  position: absolute;
  top: 5.375rem;
  left: 0.625rem;
}
.top-right {
  position: absolute;
  top: 5.375rem;
  right: 0.625rem;
}
.left-bottom {
  position: absolute;
  left: 0.625rem;
  bottom: 3.625rem;
}
.right-bottom {
  position: absolute;
  right: 0.625rem;
  bottom: 3.625rem;
}
.btn-icon-group {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.btn-icon {
  width: 3rem;
  height: 3rem;
  margin-bottom: 0.5rem;
  background: #fff;
  border-radius: 0.375rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.icon-name {
  font-size: 0.625rem;
  color: #333;
  height: 0.9375rem;
  line-height: 0.9375rem;
  margin-top: 0.0625rem;
}
.layer-box {
  padding: 3px 5px;
}
.layer-sl {
  margin-left: 5px;
}
/* 区域覆盖物样式 */
.region-container {
  background-size: 100% 100%;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  backdrop-filter: blur(20px);
  width: 80px;
  height: 40px;
  border: 1px solid RGBA(144, 184, 206, 0.8);
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  .region-xzqmc {
    font-size: 10px;
    color: #ffffffb3;
  }
  .region-icon {
    width: 20px;
    height: 20px;
    margin-right: 6px;
  }
  .region-count {
    font-size: 14px;
    margin-top: 2px;
    color: #fff;
    font-weight: 700;
  }
}

.ks-container {
  width: 90vw;
  display: flex;
  flex-direction: column;
  padding: 10px;
  box-sizing: border-box;
  .ks-title-box {
    height: 40px;
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .ks-title-text {
      font-weight: 500;
      font-size: 18px;
      color: #333333;
      text-align: center;
    }
  }
}
::v-deep .van-collapse-item__title {
  display: flex;
  align-items: center;
}
::v-deep .van-cell__left-icon {
  display: flex;
  align-items: center;
  padding-bottom: 2px;
}
::v-deep .van-cell__title {
  display: flex;
  align-items: center;
}
::v-deep .van-cell__right-icon {
  display: none;
}
.ks-item {
  height: 40px;
  line-height: 40px;
  color: #666;
  font-size: 14px;
  /* 新增文本溢出控制 */
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 溢出部分显示省略号 */
}
.kzgl-statistics {
  background-color: #fff;
  display: flex;
  flex-direction: column;
}
.statistic-navbar {
  width: calc(100vw - 24px);
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
}
.statistic-navbar-title {
  font-weight: 800;
  font-size: 18px;
  color: #000;
}
</style>

<style lang="scss">
.custom-tooltip {
  color: #ffffff;
  padding: 8px 16px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
}
.font-14 {
  font-size: 14px;
}
.font-12 {
  font-size: 12px;
}
</style>
